package etcd

import (
	"github.com/google/wire"
	"github.com/opentracing/opentracing-go/log"
	"github.com/spf13/viper"
	"go.etcd.io/etcd/clientv3"
	"strings"
	"time"
)

type Options struct {
	Test   string
	Aliyun string
	Online string
}

func NewOptions(v *viper.Viper) (*Options, error) {
	var (
		err error
		o   = new(Options)
	)
	if err = v.UnmarshalKey("etcd", o); err != nil {
		return nil, err
	}

	return o, err
}

func New(o *Options) (map[string]*clientv3.Client, error) {
	m := make(map[string]*clientv3.Client)
	endpoints := strings.Split(o.Test, ",")
	cli, err := clientv3.New(clientv3.Config{
		Endpoints:   endpoints,
		DialTimeout: 5 * time.Second,
	})
	if err != nil {
		log.Error(err)
	}
	m["test"] = cli

	endpoints1 := strings.Split(o.Aliyun, ",")
	cli1, err := clientv3.New(clientv3.Config{
		Endpoints:   endpoints1,
		DialTimeout: 5 * time.Second,
	})
	if err != nil {
		log.Error(err)
	}
	m["aliyun"] = cli1

	endpoints2 := strings.Split(o.Online, ",")
	cli2, err := clientv3.New(clientv3.Config{
		Endpoints:   endpoints2,
		DialTimeout: 5 * time.Second,
	})
	if err != nil {
		log.Error(err)
	}
	m["online"] = cli2

	return m, nil
}

var ProviderSet = wire.NewSet(New, NewOptions)
